<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户编号" prop="userId" v-if="isAuth()">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单总价" prop="totalPrice" v-if="isAuth()||isDriver()">
        <el-input
          v-model="queryParams.totalPrice"
          placeholder="请输入订单总价"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item  v-if="isAuth()||isDriver()">
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="Plus"-->
<!--          @click="handleAdd"-->

<!--        >新增</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="Edit"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->

<!--        >修改</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-if="isAuth()||isDriver()"
        >删除</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单编号" align="center" prop="id" />
      <el-table-column label="用户编号" align="center" prop="userId"  v-if="isAuth()"/>
      <el-table-column label="订单总价" align="center" prop="totalPrice"  v-if="isAuth()||isDriver()"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
<!--          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" >修改</el-button>-->
          <el-button link type="primary" icon="Edit" @click="handleSee(scope.row)" >查看</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"  v-if="isAuth()||isDriver()">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        v-show="total>0"
        :total="total"
        v-model:current-page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @current-change="getList"
    />

    <!-- 添加或修改订单对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="orderRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户编号" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户编号" />
        </el-form-item>
        <el-form-item label="订单总价" prop="totalPrice">
          <el-input v-model="form.totalPrice" placeholder="请输入订单总价" />
        </el-form-item>
<!--        <el-form-item label="${comment}" prop="delFlag">-->
<!--          <el-input v-model="form.delFlag" placeholder="请输入${comment}" />-->
<!--        </el-form-item>-->
        <el-divider content-position="center">订单货源明细信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddOrderGoodsDetails">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteOrderGoodsDetails">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="orderGoodsDetailsList" :row-class-name="rowOrderGoodsDetailsIndex" @selection-change="handleOrderGoodsDetailsSelectionChange" ref="orderGoodsDetails">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

<!--  查看订单详情  -->
    <el-dialog :title="title" v-model="seeOpen" width="500px" append-to-body>
      <div v-for="goods in goodsList">
        <p>货源:{{goods.name}}</p>
        <p>价格:{{goods.price}}</p>
        <p>产地:{{goods.address}}</p>
        <el-divider content-position="center"/>
      </div>
      <div v-if="!isAuth()&&isGoodsOwner">
        <h5>接单司机信息</h5>
        <p>昵称:{{driver.nickName}}</p>
        <p>邮箱:{{driver.email}}</p>
        <p>性别:{{driver.gender===0?'女':'男'}}</p>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Order">
import { listOrder, getOrder, delOrder, addOrder, updateOrder } from "@/api/order";
import {getCurrentInstance, reactive, ref, toRaw, toRefs} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {isAuth, isDriver, isGoodsOwner, parseTime} from "@/utils/common";
import request from "@/utils/request";
const { proxy } = getCurrentInstance();

const orderList = ref([]);
const orderGoodsDetailsList = ref([]);
const open = ref(false);
const seeOpen = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedOrderGoodsDetails = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const goodsList=ref([])
const driver=ref({});

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    totalPrice: null,
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询订单列表 */
function getList() {
  loading.value = true;
  listOrder(queryParams.value).then(response => {
    orderList.value = response.data.records;
    total.value = response.data.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    userId: null,
    totalPrice: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null
  };
  orderGoodsDetailsList.value = [];
  proxy.resetForm("orderRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加订单";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getOrder(_id).then(response => {
    form.value = response.data;
    orderGoodsDetailsList.value = response.data.orderGoodsDetailsList;
    open.value = true;
    title.value = "修改订单";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["orderRef"].validate(valid => {
    if (valid) {
      form.value.orderGoodsDetailsList = orderGoodsDetailsList.value;
      if (form.value.id != null) {
        updateOrder(form.value).then(response => {
          ElMessage.success("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addOrder(form.value).then(response => {
          ElMessage.success("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  ElMessageBox.confirm('是否确认删除订单编号为"' + _ids + '"的数据项？').then(function() {
    return delOrder(_ids);
  }).then(() => {
    getList();
    ElMessage.success("删除成功");
  }).catch(() => {});
}

/** 订单货源明细序号 */
function rowOrderGoodsDetailsIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 订单货源明细添加按钮操作 */
function handleAddOrderGoodsDetails() {
  let obj = {};
  orderGoodsDetailsList.value.push(obj);
}

/** 订单货源明细删除按钮操作 */
function handleDeleteOrderGoodsDetails() {
  if (checkedOrderGoodsDetails.value.length == 0) {
    ElMessage.error("请先选择要删除的订单货源明细数据");
  } else {
    const orderGoodsDetailss = orderGoodsDetailsList.value;
    const checkedOrderGoodsDetailss = checkedOrderGoodsDetails.value;
    orderGoodsDetailsList.value = orderGoodsDetailss.filter(function(item) {
      return checkedOrderGoodsDetailss.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handleOrderGoodsDetailsSelectionChange(selection) {
  checkedOrderGoodsDetails.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('yang/order/export', {
    ...queryParams.value
  }, `order_${new Date().getTime()}.xlsx`)
}

function handleSee(row) {
  reset();
  const _id = row.id || ids.value
  getOrder(_id).then(response => {
    driver.value=response.data.driver;
    goodsList.value = response.data.goods;
    seeOpen.value = true;
    title.value = "查看订单详情";
  });
}

getList();
</script>
